package com.example.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.*;
import com.example.service.IProductService;
import com.example.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：zhuang
 * 日期：2024/6/19 10:18
 */
@RestController
@RequestMapping("/admin/product")
public class AdminProductController {
    @Autowired
    private IProductService productService;

    @Value("${productImagesFilePath}")
    private String productImagesFilePath;

    @Value("${swiperImagesFilePath}")
    private String swiperImagesFilePath;
    @Value("${productIntroImgsFilePath}")
    private String productIntroImgsFilePath;
    /**
     * 根据条件分页查询
     * @param pageBean
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        Map<String,Object> map=new HashMap<>();
        map.put("name",pageBean.getQuery().trim());
        map.put("start",pageBean.getStart());
        map.put("pageSize",pageBean.getPageSize());
        List<Product> productList=productService.list(map);
        Long total=productService.getTotal(map);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("productList",productList);
        resultMap.put("total",total);
        return R.ok(resultMap);
    }

    /**
     * 更新是否热卖，幻灯片
     * @param id
     * @param hot
     * @return
     */
    @GetMapping("/updateHot/{id}/state/{hot}")
    public R updateHot(@PathVariable (value = "id")Integer id, @PathVariable(value = "hot")boolean hot) {
        Product product = productService.getById(id);
        product.setHot(hot);
        if(hot){
            product.setHotDateTime(new Date());
        }else {
            product.setHotDateTime(null);
        }
        productService.saveOrUpdate(product);
        return R.ok();
    }

    /**
     * 更新swiper状态
     * @param id
     * @param swiper
     * @return
     */
    @GetMapping("/updateSwiper/{id}/state/{swiper}")
    public R updateSwiper(@PathVariable (value = "id")Integer id, @PathVariable(value = "swiper")boolean swiper) {
        Product product = productService.getById(id);
        product.setSwiper(swiper);
        productService.saveOrUpdate(product);
        return R.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id){

        productService.removeById(id);
        return R.ok();
    }
    //批量删除
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            productService.removeById(id);
        }
        return R.ok();
    }

    /**
     * 上传商品大类图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(productImagesFilePath+newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","/image/product/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }

    /**
     * 上传幻灯图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadSwiperImage")
    public Map<String,Object> uploadSwiperImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(swiperImagesFilePath+newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","/image/swiper/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }
    /**
     * 上传商品图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadProductImage")
    public ResponseEntity<Map<String, Object>> uploadProductImage(MultipartFile file) {
        Map<String, Object> resultMap = new HashMap<>();

        if (file.isEmpty()) {
            resultMap.put("code", 1);
            resultMap.put("msg", "文件为空");
            return ResponseEntity.badRequest().body(resultMap);
        }
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!isValidImageType(suffixName)) {
            resultMap.put("code", 2);
            resultMap.put("msg", "仅支持 JPG, PNG, GIF 格式的文件");
            return ResponseEntity.badRequest().body(resultMap);
        }
        try {
            // 生成唯一文件名
            String newFileName = System.currentTimeMillis() + suffixName;
            File targetFile = new File(productIntroImgsFilePath + newFileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);

            resultMap.put("code", 0);
            resultMap.put("msg", "上传成功");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("title", newFileName);
            dataMap.put("src", "/image/productIntroImgs/" + newFileName);
            resultMap.put("data", dataMap);

            return ResponseEntity.ok(resultMap);

        } catch (IOException e) {
            resultMap.put("code", 3);
            resultMap.put("msg", "上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
        }
    }

    private boolean isValidImageType(String suffix) {
        return ".jpg".equalsIgnoreCase(suffix) ||
                ".jpeg".equalsIgnoreCase(suffix) ||
                ".png".equalsIgnoreCase(suffix) ||
                ".gif".equalsIgnoreCase(suffix);
    }
    /**
     * 添加或者修改
     * @param product
     * @return
     */
    @RequestMapping("/save")
    public R save(@RequestBody Product product){
        if(product.getId()==null || product.getId()==-1){
            productService.add(product);
        }else{
            productService.update(product);
        }
        return R.ok();
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        Product product = productService.findById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("product",product);
        return R.ok(map);
    }

    /**
     * 根据商品大类id查询所有小类
     * @param smallTypeId
     * @return
     */
    @GetMapping("/listAll/{smallTypeId}")
    public R listAll(@PathVariable(value = "smallTypeId")Integer smallTypeId){
        Map<String,Object> map=new HashMap<>();
        map.put("productList",productService.list(new QueryWrapper<Product>().eq("typeId",smallTypeId)));
        return R.ok(map);
    }
}